package com.healthybear.demo.languagechange

import android.app.Dialog
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.widget.ProgressBar
import android.widget.TextView
import androidx.appcompat.app.AlertDialog

/**
 * LoadingDialogManager handles loading dialog functionality with timeout and proper lifecycle management
 * 
 * Requirements addressed:
 * - 7.1: Display loading dialog during language switching
 * - 7.2: Prevent additional language change requests during loading
 * - 7.3: Dismiss loading dialog when operation completes
 */
class LoadingDialogManager(private val context: Context) {
    
    private var loadingDialog: AlertDialog? = null
    private var timeoutHandler: Handler? = null
    private var timeoutRunnable: Runnable? = null
    private var isShowing = false
    
    companion object {
        private const val TAG = "LoadingDialogManager"
        private const val DEFAULT_TIMEOUT_MS = 5000L // 5 seconds timeout
    }
    
    /**
     * Show loading dialog with progress indicator
     * Requirement 7.1: Display loading dialog during language switching
     */
    fun showLoadingDialog(
        message: String = context.getString(R.string.loading_language_change),
        timeoutMs: Long = DEFAULT_TIMEOUT_MS,
        onTimeout: (() -> Unit)? = null
    ) {
        try {
            // Don't show if already showing
            if (isShowing) {
                Log.w(TAG, "Loading dialog already showing, ignoring request")
                return
            }
            
            // Create custom layout for loading dialog
            val dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_loading, null)
            val messageTextView = dialogView.findViewById<TextView>(R.id.loadingMessage)
            val progressBar = dialogView.findViewById<ProgressBar>(R.id.loadingProgressBar)
            
            messageTextView.text = message
            
            // Create and configure dialog
            loadingDialog = AlertDialog.Builder(context)
                .setView(dialogView)
                .setCancelable(false)
                .create()
            
            // Set up timeout handling
            setupTimeout(timeoutMs, onTimeout)
            
            loadingDialog?.show()
            isShowing = true
            
            Log.d(TAG, "Loading dialog shown with message: $message")
            
        } catch (e: Exception) {
            Log.e(TAG, "Failed to show loading dialog", e)
            isShowing = false
        }
    }
    
    /**
     * Dismiss the loading dialog
     * Requirement 7.3: Dismiss loading dialog when operation completes
     */
    fun dismissLoadingDialog() {
        try {
            cancelTimeout()
            
            loadingDialog?.let { dialog ->
                if (dialog.isShowing) {
                    dialog.dismiss()
                    Log.d(TAG, "Loading dialog dismissed")
                }
            }
            
            loadingDialog = null
            isShowing = false
            
        } catch (e: Exception) {
            Log.e(TAG, "Failed to dismiss loading dialog", e)
            isShowing = false
        }
    }
    
    /**
     * Check if loading dialog is currently showing
     * Requirement 7.2: Prevent additional language change requests during loading
     */
    fun isLoadingDialogShowing(): Boolean {
        return isShowing && loadingDialog?.isShowing == true
    }
    
    /**
     * Set up timeout handling for the loading dialog
     */
    private fun setupTimeout(timeoutMs: Long, onTimeout: (() -> Unit)?) {
        if (timeoutMs <= 0) return
        
        timeoutHandler = Handler(Looper.getMainLooper())
        timeoutRunnable = Runnable {
            Log.w(TAG, "Loading dialog timeout reached ($timeoutMs ms)")
            dismissLoadingDialog()
            onTimeout?.invoke()
        }
        
        timeoutHandler?.postDelayed(timeoutRunnable!!, timeoutMs)
    }
    
    /**
     * Cancel the timeout handler
     */
    private fun cancelTimeout() {
        timeoutRunnable?.let { runnable ->
            timeoutHandler?.removeCallbacks(runnable)
        }
        timeoutHandler = null
        timeoutRunnable = null
    }
    
    /**
     * Clean up resources - should be called in onDestroy or similar lifecycle methods
     */
    fun cleanup() {
        dismissLoadingDialog()
        cancelTimeout()
    }
}